﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Collections;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using RestSharp;
using System.Diagnostics;
using System.Device;
using System.IO;
using System.Text;
using Microsoft.Phone.Shell;

namespace unifiqAnthony
{
    public partial class AddSuggestion : PhoneApplicationPage
    {
        private static string API_KEY = "AoetA0820tVc4COdo9bGyEKy0mBSDjoSeb9vlIRP3iC3RWibRFlwOGPGVLOUn7Fs";
        private List<RequestData> requestDataList = new List<RequestData>();
        private string eventTitle, postData;
        private int eventID, userID;

        public AddSuggestion()
        {
            InitializeComponent();
            User user = (User)PhoneApplicationService.Current.State["currentUser"];
            userID = user.uid;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            eventTitle = NavigationContext.QueryString["eventTitle"];
            eventID = Convert.ToInt32(NavigationContext.QueryString["eventID"]);

            title_tb.Text = eventTitle;
        }

        private void comment_tb_MouseEnter(object sender, MouseEventArgs e)
        {
            if (comment_tb.Text.Equals("Enter comment if any"))
            {
                comment_tb.Text = "";
            }
        }

        private void comment_tb_MouseLeave(object sender, MouseEventArgs e)
        {
            if (comment_tb.Text.Equals(""))
            {
                comment_tb.Text = "Enter comment if any";
            }
        }

        private void location_autocomplete_TextChanged(object sender, RoutedEventArgs e)
        {
            location_lp.Items.Clear();
            string loadingMsg = "Loading locations...";
            location_lp.Items.Add(loadingMsg);
            string locationURL = "https://dev.virtualearth.net/REST/v1/Locations?q=" + location_autocomplete.Text + "&maxResults=10&key=" + API_KEY;
            var autoCompleteClient = new RestClient(locationURL);
            var locationRequest = new RestRequest();
            locationRequest.Method = Method.GET;
            locationRequest.RequestFormat = DataFormat.Json;
            List<string> dataSource = new List<string>();
            autoCompleteClient.ExecuteAsync(locationRequest, response =>
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    requestDataList.Clear();
                    var json = response.Content;
                    var jsonObject = JObject.Parse(json);
                    var dict = JsonConvert.DeserializeObject<RootObject>(json);
                    var resources = dict.resourceSets[0].resources;
                    foreach (var item in resources)
                    {
                        if (item.address.countryRegion.Equals("Singapore"))
                        {
                            RequestData requestData = new RequestData();
                            requestData.addressString = item.address.formattedAddress.Split(',')[0];
                            requestData.state = item.address.adminDistrict;
                            requestData.city = item.address.adminDistrict2;
                            requestData.country = item.address.countryRegion;
                            requestData.latitude = item.geocodePoints[0].coordinates[0].ToString();
                            requestData.longitude = item.geocodePoints[0].coordinates[1].ToString();
                            requestData.LocationDisplay = item.address.formattedAddress.Split(',')[0];

                            if (!string.IsNullOrWhiteSpace(item.address.adminDistrict2))
                                requestData.LocationDisplay = requestData.LocationDisplay + ", " + item.address.adminDistrict2;
                            if (!string.IsNullOrWhiteSpace(item.address.adminDistrict))
                                requestData.LocationDisplay = requestData.LocationDisplay + ", " + item.address.adminDistrict;

                            if (location_lp.Items[0].Equals(loadingMsg))
                            {
                                location_lp.Items.Clear();
                            }

                            location_lp.Items.Add(requestData.LocationDisplay);
                            requestDataList.Add(requestData);
                        }
                    }
                }
            });
        }

        private void map_btn_Click(object sender, RoutedEventArgs e)
        {
            if (location_lp.Items.Count > 0)
            {
                RequestData requestData = requestDataList[location_lp.SelectedIndex];
                location_autocomplete.Text = requestData.addressString.Split(',')[0];

                if (!string.IsNullOrWhiteSpace(requestData.city))
                    location_autocomplete.Text = location_autocomplete.Text + ", " + requestData.city;
                if (!string.IsNullOrWhiteSpace(requestData.state))
                    location_autocomplete.Text = location_autocomplete.Text + ", " + requestData.state;
                if (!string.IsNullOrWhiteSpace(requestData.country))
                    location_autocomplete.Text = location_autocomplete.Text + ", " + requestData.country;

                NavigationService.Navigate(new Uri("/ShowMap.xaml?location=" + location_autocomplete.Text + "&lat=" + requestData.latitude + "&lng=" + requestData.longitude, UriKind.Relative));
            }
        }

        private void location_lp_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            location_autocomplete.Text = location_lp.SelectedItem.ToString();
        }

        private void submit_btn_Click(object sender, RoutedEventArgs e)
        {
            if (location_cb.IsChecked == true || date_cb.IsChecked == true|| time_cb.IsChecked == true || comment_cb.IsChecked == true)
            {
                bool valid = true;

                if (location_cb.IsChecked == true && location_lp.Items.Count <= 0)
                {
                    MessageBox.Show("Please enter an event location", "Event location field required", MessageBoxButton.OK);
                    valid = false;
                }
                else if (date_cb.IsChecked == true && date_picker.Value.Value.Date.CompareTo(DateTime.Now.Date) < 0)
                {
                    MessageBox.Show("Please enter a valid event date", "Event date has passed", MessageBoxButton.OK);
                    valid = false;
                }
                else if (comment_cb.IsChecked == true && comment_tb.Text.Equals("Enter comment if any"))
                {
                    MessageBox.Show("Please enter your comment", "Comment field required", MessageBoxButton.OK);
                    valid = false;
                }

                if (valid)
                {
                    postData = "&condition=(" + userID.ToString() + ", " + eventID.ToString() + ", ";
                    
                    //postData += "&date=";
                   if (date_cb.IsChecked == true)
                    {                    
                        string[] tempDateArr = date_picker.Value.ToString().Split('/');
                        string date = tempDateArr[2].Substring(0, 4) + "-" + tempDateArr[0] + "-" + tempDateArr[1];

                        postData += "'" + date + "', ";
                    }
                   else{
                       postData += "null, ";
                   }

                  // postData += "&time=";
                   if (time_cb.IsChecked == true)
                   {
                       string time;

                       string[] tempTimeArr = time_picker.Value.ToString().Split(' ');
                       if (tempTimeArr[2].Equals("PM"))
                       {
                           time = (12 + Convert.ToInt32(tempTimeArr[1].Split(':')[0])).ToString() + ":" + tempTimeArr[1].Split(':')[1] + ":" + tempTimeArr[1].Split(':')[2];
                       }
                       else
                       {
                           time = tempTimeArr[1];
                       }

                       postData += "'" + time + "', ";
                   }
                   else
                   {
                       postData += "null, ";
                   }
 
                   if (location_cb.IsChecked == true)
                   {
                       RequestData requestData = requestDataList[location_lp.SelectedIndex];
                       string lat = requestData.latitude;
                       string lng = requestData.longitude;

                       postData += lat + ", " + lng;
                   }
                   else
                   {
                       postData += "null, null, ";
                   }

                   //postData += "&comment=";
                   if (comment_cb.IsChecked == true)
                   {
                       postData += "'" + comment_tb.Text + "')";
                   }
                   else
                   {
                       postData += "null)";
                   }

                   Debug.WriteLine(postData);
                     var url = "http://unifiq.5kportal.com/create_event_suggestion.php";


                    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                    webRequest.Method = "POST";
                    webRequest.ContentType = "application/x-www-form-urlencoded";

                    webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
                    MessageBox.Show("Event suggestion successfully created!");
                    location_autocomplete.Text = "";
                    location_lp.Items.Clear();
                    comment_tb.Text = "Enter event comment";

                    location_cb.IsChecked = false;
                    date_cb.IsChecked = false;
                    time_cb.IsChecked = false;
                    comment_cb.IsChecked = false;

                }
            }
        }

        void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
            // End the stream request operation
            Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);

            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
        }

        void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
                HttpWebResponse response;

                // End the get response operation
                response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
                Stream streamResponse = response.GetResponseStream();
                StreamReader streamReader = new StreamReader(streamResponse);
                var Response = streamReader.ReadToEnd();
                streamResponse.Close();
                streamReader.Close();
                response.Close();

            }
            catch (WebException e)
            {
                MessageBox.Show(e.ToString());
            }
        }

    }
}